package com.opennews.openplatform.config;

import com.opennews.openplatform.controller.AuthInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerTypePredicate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@RequiredArgsConstructor
@Configuration
public class WebConfig implements WebMvcConfigurer {
    public final static String API_PATH_PREFIX = "api";

    private final AuthInterceptor authInterceptor;
    private final Environment env;

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.addPathPrefix(API_PATH_PREFIX, HandlerTypePredicate.forAnnotation(RestController.class));
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor)
                .addPathPatterns(String.format("/%s/**", API_PATH_PREFIX));
    }

    /**
     * Serves local content as web server static resource via embedded tomcat.
     */
    /**
     * https://www.baeldung.com/spring-mvc-static-resources
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // IMPORTANT!!!
        // Never includes leading slash for addResourceLocations. Otherwise you would encounter error: java.net.UnknownHostException.
        // And this error leads to "Resolved [org.springframework.http.converter.HttpMessageNotWritableException:
        // No converter for [class java.util.LinkedHashMap] with preset Content-Type 'image/jpeg;charset=UTF-8']"
        //
        // The correct value is like: file:/opt/files/
        // NOT file://opt/files/
        // NOT file:opt/files/
        String rootFilePath = env.getProperty("resource.upload.rootFilePath");

        // Removes all leading slashes if existed.
        // In Java, String.replaceFirst(String regex, String replacement) interprets the first argument as a regular expression.
        String resourceLocation = rootFilePath.replaceFirst("^/*", "");

        registry.addResourceHandler(String.format("/%s/**", env.getProperty("resource.base-name")))
                .addResourceLocations("file:/" + resourceLocation);
    }
}
